﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Common
{
    public class SoftAuthorize
    {

        private string machine_code = "";
        private SoftAuthorize() { }
        /// <summary>
        /// 窗体对象实例
        /// </summary>
        private static SoftAuthorize _instance;
        public static SoftAuthorize Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new SoftAuthorize();
                _instance.machine_code = SoftAuthorize.GetInfo();
                return _instance;
            }
        }





        public string GetMachineCodeString()
        {
            return this.machine_code;
        }



        public bool IsRegistered(string code)
        {
            return CheckAuthorize(code, AuthorizeEncrypted);
        }

        public string GetReRegisteredCode(string origin)
        {
            return AuthorizeEncrypted(origin);
        }


        private bool CheckAuthorize(string code, Func<string, string> encrypt)
        {
            if (code != encrypt(this.GetMachineCodeString()))
                return false;
            return true;
        }


        /// <summary>
        /// 一个自定义的加密方法，传入一个原始数据，返回一个加密结果
        /// </summary>
        /// <param name="origin">原始的</param>
        /// <returns></returns>
        private string AuthorizeEncrypted(string origin)
        {
            // 此处使用了组件支持的DES对称加密技术
            return SoftSecurity.MD5Encrypt(origin, "song1122");
        }



        private static string GetInfo()
        {
         
            string machineCode = string.Format("{0}-{1}", LocalMachineHelper.GetCPUSerialNumber(), LocalMachineHelper.GetHardDiskID());
            return ByteToHexString(new MD5CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes(machineCode)));
        }


  

        private static string ByteToHexString(byte[] InBytes)
        {
            return ByteToHexString(InBytes, char.MinValue);
        }

        private static string ByteToHexString(byte[] InBytes, char segment)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte inByte in InBytes)
            {
                if (segment == char.MinValue)
                    stringBuilder.Append(string.Format("{0:X2}", (object)inByte));
                else
                    stringBuilder.Append(string.Format("{0:X2}{1}", (object)inByte, (object)segment));
            }
            if (segment != char.MinValue && stringBuilder.Length > 1 && (int)stringBuilder[stringBuilder.Length - 1] == (int)segment)
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
            return stringBuilder.ToString();
        }
    }
}
